package mall.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import mall.pojo.Cart;
import mall.pojo.Item;
import mall.pojo.Member;
import mall.pojo.Orderdetail;
import mall.pojo.OrderdetailId;
import mall.pojo.Orders;
import mall.pojo.Product;
import mall.pojo.Shop;
import mall.service.OrderDetailService;
import mall.service.OrderService;
import mall.service.ProductService;
import mall.service.ShopService;
import mall.util.UtilityClass;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@Scope("request")
public class OrderController {

	@Autowired
	private OrderService orderService;
	@Autowired
	private OrderDetailService orderDetailService;
	@Autowired
	private ProductService productService;
	@Autowired
	private ShopService shopService;

	@Autowired
	private Cart cart;

	@RequestMapping(value = "/checkout", method = RequestMethod.GET)
	public ModelAndView checkOut(HttpSession session) {
		ModelAndView modelAndView = new ModelAndView();
		StringBuilder detailPrice = new StringBuilder();
		float total = 0;
		int shopId = Integer
				.parseInt(session.getAttribute("shopId").toString());
		Shop shop = shopService.getShop(shopId);
		List<Item> listItem = cart.getItems();
		for (int i = 0; i < listItem.size(); i++) {
			Item item = listItem.get(i);
			int orderQuantity = item.getQuantity();
			Product product = productService.getProduct(item.getProductid());
			if (orderQuantity > product.getQuantity()) {
				// listItem.remove(item);
				// cart.getItems().remove(item);
				cart.getItems().get(i).setAvailable(false);
			} else {
				detailPrice.append(item.getTotal() + " + ");
				total += item.getTotal();
			}
		}
		session.setAttribute("total", total);
		// delete 3 ky tu cuoi cung
		if (detailPrice.length() > 3)
			detailPrice.delete(detailPrice.length() - 3, detailPrice.length());

		modelAndView.addObject("detailPrice", detailPrice.toString());
		modelAndView.addObject("total", total);
		modelAndView.addObject("payment_id", shop.getPaymentUsername());
		modelAndView.addObject("LOGGED_IN", UtilityClass.LOGGED_IN);
		modelAndView.addObject("NOT_LOGGED_IN", UtilityClass.NOT_LOGGED_IN);
		Member member = (Member) session.getAttribute("userInfo");
		modelAndView.setViewName(UtilityClass.VIEW_SHOP_CHECKOUT);
		if (member == null) {
			modelAndView.addObject("LOGIN_STATUS", UtilityClass.NOT_LOGGED_IN);

		} else {
			modelAndView.addObject("LOGIN_STATUS", UtilityClass.LOGGED_IN);
			modelAndView.addObject("orders", new Orders());
		}
		return modelAndView;

	}

	// save order into database
	@RequestMapping(value = "/makeorder", method = RequestMethod.POST)
	public String makeOrder(@ModelAttribute("order") Orders order,
			BindingResult bindingResult, HttpSession session) {
		// ModelAndView modelAndView = new ModelAndView();
		// save order
		Member member = (Member) session.getAttribute("userInfo");
		int shopId = Integer
				.parseInt(session.getAttribute("shopId").toString());
		Shop shop = shopService.getShop(shopId);
		shop.setId(shopId); // create new shop with id of current shop
		order.setMember(member);
		order.setDate(new Date());
		order.setShop(shop);

		orderService.createOrder(order); // save order into database

		// save orderdetail
		List<Item> listItem = cart.getItems();
		for (Item item : listItem) { // iterate list item of cart and save into
										// orderdetail table
			Orderdetail orderdetail = new Orderdetail();
			orderdetail.setOrders(order);
			if (item.isAvailable()) { // only save items that available (order
										// quantity < quantity exists)
				Product product = new Product(); // create new product and set
													// product id
				product.setId(item.getProductid());
				// set orderdetail
				orderdetail.setProduct(product);
				orderdetail.setPrice(item.getPrice());
				orderdetail.setQuantity(item.getQuantity());
				orderdetail.setName(item.getName());
				orderdetail.setId(new OrderdetailId(order.getId(), item
						.getProductid()));
				orderDetailService.createOrderDetail(orderdetail);
			}
		}

		if (order.getPaymentmethod() == 0) { // pay by cash , redirect
			return "redirect:home-shop";
		} else { // online payment , redirec to payment-gateway
			float total = Float.parseFloat(session.getAttribute("total")
					.toString());
			String shop_acc = shop.getPaymentUsername();
			String order_id = order.getId().toString();
			System.out.println(total);
			return "redirect:http://localhost:8080/payment-gateway/Payment?total="
					+ total
					+ "&shop_acc="
					+ shop_acc
					+ "&orders_id="
					+ order_id;
		}
		// modelAndView.setViewName(UtilityClass.VIEW_SHOP_CHECKOUT);

	}

	@RequestMapping(value = "/update-payment", method = RequestMethod.GET)
	public String updatePayment(@RequestParam("orders_id") int orderId,
			@RequestParam("errcode") int errorCode, HttpSession session) {
		int shopId=0;
		if(errorCode==UtilityClass.PAYMENT_ERROR_CODE_SUCCESS){ // success, update payment method
			Orders orders=orderService.getOrder(orderId);
			orders.setPaymentmethod(UtilityClass.PAYMENT_METHOD_ONLINEPAYMENT_FINISHED);
			orderService.updateOrder(orders);
			shopId=orders.getShop().getId();
		}else{
			if(errorCode==UtilityClass.PAYMENT_ERROR_CODE_FAIL){
				Orders orders=orderService.getOrder(orderId);
				orders.setPaymentmethod(UtilityClass.PAYMENT_METHOD_CASH);
				orderService.updateOrder(orders);
				shopId=orders.getShop().getId();
			}
		}
		return "redirect:index-shop?shopid="+shopId+"&catid=-1";
	}

	@RequestMapping(value = "/manage-shop-order", method = RequestMethod.GET)
	public ModelAndView listOrder(HttpSession session) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName(UtilityClass.VIEW_SHOP_ORDER_ADMIN);
		int shopId = Integer
				.parseInt(session.getAttribute("shopId").toString());
		modelAndView.addObject("listorder", orderService.getOrderShop(shopId));
		return modelAndView;
	}

	@RequestMapping(value = "/changestate", method = RequestMethod.GET)
	public ModelAndView changeState(@RequestParam("id") int orderId,
			@RequestParam("state") int state, HttpSession session) {
		ModelAndView modelAndView = new ModelAndView();
		Orders orders = orderService.getOrder(orderId);
		orders.setState(state);
		orderService.updateOrder(orders);
		int shopId = Integer
				.parseInt(session.getAttribute("shopId").toString());
		modelAndView.addObject("listorder", orderService.getOrderShop(shopId));
		modelAndView.setViewName(UtilityClass.VIEW_SHOP_ORDER_ADMIN);
		return modelAndView;
	}
}
